#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QFile>
#include <QIODevice>
#include <stdlib.h>
#include <stdio.h>

MainWindow::MainWindow()
{
    ui.setupUi(this);

    QObject::connect(ui.pushButton_3, SIGNAL(clicked()), this, SLOT(add()));
    QObject::connect(ui.pushButton_2, SIGNAL(clicked()), this, SLOT(exit()));
    QObject::connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(save()));
    QObject::connect(ui.listWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(showData(QListWidgetItem *)));

    readFile();

    for (int i=0; i!= vecInfa.size(); ++i)
        writeToList(&vecInfa[i]);
}

void MainWindow::readFile()
{
    QFile file("in.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QVector<QString> tmp;
    QTextStream in(&file);
    while (!in.atEnd())
    {
        QString line = in.readLine();
        tmp.append(line);
    }

    int i=0;
    while(i!= tmp.size())
    {
        Info inf(tmp[i], tmp[i+1], tmp[i+2], tmp[i+3]);
        vecInfa.append(inf);
        i+=4;
    }

}

void MainWindow::writeToList(Info *infItem)
{
    QByteArray data;
    data.append(infItem->m_lastName + " " + infItem->m_firstName);

    QString d(data);
    ui.listWidget->addItem(d);
}

void MainWindow::showData(QListWidgetItem * item)
{
    int i=0;
    for (; i!=vecInfa.size(); ++i)
    {
        if (item->text() == (vecInfa[i].m_lastName + " " + vecInfa[i].m_firstName))
            break;
    }

    ui.lineEdit->setText(vecInfa[i].m_lastName);
    ui.lineEdit_2->setText(vecInfa[i].m_firstName);
    ui.lineEdit_3->setText(vecInfa[i].m_tel);
    ui.lineEdit_4->setText(vecInfa[i].m_email);
    ui.lineEdit_5->setText(QString::number(i));
}

void MainWindow::add()
{
    Info inf(ui.lineEdit->text(), ui.lineEdit_2->text(), ui.lineEdit_3->text(), ui.lineEdit_4->text() );
    
    vecInfa.append(inf);
    writeToList(&inf);    
}

void MainWindow::exit()
{
    QFile file("in.txt");
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    QTextStream out(&file);
    for (int i=0; i!=vecInfa.size(); ++i)
        out << vecInfa[i].m_lastName<<"\n"<< vecInfa[i].m_firstName<< "\n"<< vecInfa[i].m_tel <<"\n"<< vecInfa[i].m_email<< "\n";
    file.close();

    this->close();
}

void MainWindow::save()
{
    if (ui.lineEdit_5->text() != "not defined")
    {
        int i = (ui.lineEdit_5->text()).toInt();
        vecInfa[i].m_lastName = ui.lineEdit->text();
        vecInfa[i].m_firstName = ui.lineEdit_2->text();
        vecInfa[i].m_tel = ui.lineEdit_3->text();
        vecInfa[i].m_email = ui.lineEdit_4->text();

        QListWidgetItem * item= ui.listWidget->item(i);
        if (item->text() != (vecInfa[i].m_lastName + " " + vecInfa[i].m_firstName))
            item->setText(vecInfa[i].m_lastName + " " + vecInfa[i].m_firstName);
    }
}







